<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入项目名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="warning" icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['business:projects:add']">新增</el-button>
      </el-form-item>
    </el-form>

    <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['business:projects:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['business:projects:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['business:projects:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['business:projects:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row> -->

    <el-table v-loading="loading" :data="projectsList" @selection-change="handleSelectionChange" border>
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <!-- <el-table-column label="${comment}" align="center" prop="id" /> -->
      <el-table-column label="项目名称" width="200" align="left" prop="name" />
      <el-table-column label="负责人" width="200" align="center" prop="principal" >
        <template slot-scope="scope">
          <span v-for="item in principals" v-if="item.userId == scope.row.principal" >{{ item.nickName }} —— {{ item.phonenumber }}</span>
        </template>
      </el-table-column>
      <el-table-column label="项目周期" width="240" align="center" prop="description">
        <template slot-scope="scope">
          {{ scope.row.startDate }} - {{ scope.row.endDate }} ——预计 {{ scope.row.cycle }} 天
        </template>
      </el-table-column>
      <el-table-column label="介绍" align="left" prop="description" />
      <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
      <el-table-column label="操作" width="180" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-folder" @click="handleNodeList(scope.row)"
            v-hasPermi="['business:nodes:list']">进入</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['business:projects:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['business:projects:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改项目信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入项目名称" />
        </el-form-item>

        <el-form-item label="负责人" prop="principal">
          <!-- <el-input v-model="form.principal" placeholder="请输入负责人" /> -->
          <el-select v-model="form.principal" placeholder="请选择" @change="selectPrincipal" clearable >
            <el-option v-for="item in principals" :key="item.userId" :label="item.nickName + ' —— ' + item.phonenumber"
              :value="item.userId+''">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="项目周期" prop="">
          <!-- <el-input v-model="form.principal" placeholder="请输入负责人" /> -->
          <div class="block">
            <el-date-picker v-model="value1" format="yyyy-MM-dd" type="daterange" range-separator="至"
              start-placeholder="开始日期" end-placeholder="结束日期" @change="changeDate">
            </el-date-picker>
          </div>
        </el-form-item>

        <el-form-item label="项目介绍">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="选择流程" prop="remark" v-if="form.id == null">
          <div style="display: flex;flex-wrap: nowrap;justify-content: space-around;">
            <div v-for="item in flowList" class="flow-warp" :key="item.id" @click="selectFlow(item.id)">
              <!-- <img :src="baseURL + item.icon" alt="" /> -->
              <div :class=" (form.activeModel == item.id) ?'flow-item-active ':'' " class="flow-item">
                <div v-if="item.icon" class="flow-item-icon"></div>
                <div v-if="!item.icon" class="flow-item-icon_" :class=" (form.activeModel == item.id) ?'flow-item-icon_active ':'' ">+</div>
              </div>
              <div class="flow-item-name">{{ item.name }}</div>
              <div class="flow-item-description">{{ item.description }}</div>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listProjects,
    getProjects,
    delProjects,
    addProjects,
    updateProjects
  } from "@/api/business/projects";
  import {
    listPrincipals
  } from "@/api/system/user";
  import {
    listAllFlow
  } from "@/api/business/flow";

  export default {
    name: "Projects",
    dicts: ['projects_type'],
    data() {
      return {
        // 根路径
        baseURL: process.env.VUE_APP_BASE_API,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 项目信息表格数据
        projectsList: [],
        principals: [],
        flowList: [{
          name: '空白流程',
          id: 0,

        }],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          name: null,
          type: null,
          description: null,
          remark: null,
        },
        value1: '',
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          name: [{
            required: true,
            message: "名称不能为空",
            trigger: "blur"
          }]
        }
      };
    },
    watch: {
      // 监听整个路由对象变化
      $route(to, from) {
        // 当路由变化时执行逻辑
        // console.log('路由变化:', to.params, to.query);
      },
      // 监听查询参数（如 keyword）
      // '$route.query.id'(newId) {
      //   console.log('搜索关键字变化:', newId);
      //   this.queryParams.type = newId;
      //   this.form.type = newId
      //   this.getList();
      // },
    },
    created() {
      // console.log("this.$route:", this.$route.path);
      this.getPrincipals();
      this.getlistFlow();
      if (this.$route.path.indexOf('flow') > -1) {
        this.queryParams.type = 0
        this.form.type = 0
      } else if (this.$route.path.indexOf('projects') > -1) {
        this.queryParams.type = 1
        this.form.type = 1
      }
      // this.queryParams.type = this.$route.query.id;
      this.getList();
    },
    methods: {
      //**流程列表 */
      getlistFlow() {
        listAllFlow({}).then(response => {
          this.flowList.push(...response.data);
        });
      },
      /** 查询项目信息列表 */
      getList() {
        this.loading = true;
        listProjects(this.queryParams).then(response => {
          this.projectsList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      getPrincipals() {
        listPrincipals().then(response => { //获取项目负责人列表
          this.principals = response.data;
        })
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.value1 = '';
        this.form = {
          id: null,
          name: null,
          description: null,
          remark: null,
          activeModel: 0,
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加项目信息";
        this.getPrincipals();
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.getPrincipals();
        this.reset();
        const id = row.id || this.ids
        getProjects(id).then(response => {
          this.form = response.data;
          this.value1 = [this.form.startDate, this.form.endDate]
          this.open = true;
          this.title = "修改项目信息";
        });
      },
      changeDate(value) {
        this.form.startDate = value[0]
        this.form.endDate = value[1]
      },
      handleNodeList(row) {
        const id = row.id || this.ids
        this.$router.push({
          path: '/business/nodes',
          query: {
            id: id,
            type: 'project'
          }
        })
      },
      /** 提交按钮 */
      submitForm() {
        this.form.type = this.queryParams.type
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateProjects(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addProjects(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除项目信息编号为"' + ids + '"的数据项？').then(function () {
          return delProjects(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('business/projects/export', {
          ...this.queryParams
        }, `projects_${new Date().getTime()}.xlsx`)
      },
      selectFlow(item) {
        console.log(item);
        this.form.activeModel = item;
      },
      selectPrincipal(value){
        console.log(value);
      }
    }
  };

</script>
<style scoped>
  .flow-warp {
    width: 200px;
  }

  .flow-item {
    margin: 10px 10px;
    line-height: 150px;
    border: 1px solid #ccc;
    border-radius: 5px;
    cursor: pointer;
    width: 160px;
    height: 160px;
    text-align: center;
  }

  .flow-item-active {
    border: 2px solid #165dff;
  }

  .flow-item:hover {
    background-color: #f5f5f5;
  }

  .flow-item-name {
    padding: 0px 10px 0 12px;
    color: #666;
    font-weight: 600;
    line-height: 20px;
  }

  .flow-item-description {
    padding: 0px 10px 0 12px;
    color: #999;
    font-size: 12px;
  }

  .flow-item-icon_ {
    font-size: 60px;
    color: #ccc;
  }

  .flow-item-icon_active {
    color: #165dff;
  }
</style>
